import { createPortal } from 'react-dom';
import { useState } from 'react';
import * as turf from '@turf/turf';
import { Draw } from '@/compnents';
import { EditGeomIcon, ThemeTriggerIcon } from '@/compnents/icons';
import { useMapEventOnceListener } from '@/hooks';
import type { ISMap } from '@/compnents';
import './index.less';

const drawCtrCls = Draw.constants.classes.CONTROL_BUTTON;

const themes = [
  { color: '#fbb03b', style: Draw.lib.theme },
  { color: '#E1361B', style: Draw.lib.theme3 },
];
function mockCoordinate() {
  return turf.random.randomPosition([114.40505643781512, 39.1356395975223, 119.75667936801392, 41.30376077536678]);
}

function mockFeature(count = 4) {
  const coordinates = [];
  for (let i = 0; i < (count || 4); i++) coordinates.push(mockCoordinate());
  coordinates.push(coordinates[0]);
  const fc = turf.polygonSmooth(turf.bboxPolygon(turf.bbox(turf.polygon([coordinates]))), { iterations: 3 });
  return fc.features[0];
}

export const DrawCtrl = (props: { map: ISMap }) => {
  const { map } = props;
  const [container, setContainer] = useState<HTMLElement | null>(null);
  const [themeIndex, setThemeIndex] = useState(0);

  const onTheme = () => {
    const index = (themeIndex + 1) % themes.length;
    setThemeIndex(index);
    map.draw.setStyle(themes[index].style);
  };

  const onEditGeom = () => map.draw.edit(mockFeature());

  useMapEventOnceListener(map, 'draw.onAdd', (e) => {
    if (e.target.draw.displayControlsDefault) setContainer(e.data.controlContainer);
  });

  return container
    ? createPortal(
        <>
          <button
            className={drawCtrCls}
            style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}
            onClick={onEditGeom}
            title="Edit Geometry"
          >
            <EditGeomIcon className="smap-draw-edit-geom" />
          </button>
          <button className={drawCtrCls} title="Theme" onClick={onTheme} style={{ position: 'relative' }}>
            <ThemeTriggerIcon className="smap-draw-theme" themeColor={themes[themeIndex].color} />
          </button>
        </>,
        container,
      )
    : null;
};
